package com.zofer.study.sort;

import java.util.Arrays;

public class InsertSort {

    public static void main(String[] args) {
        int[] arr = {4,1,7,5,8,6,2,0};
        System.out.println("排序前的数组:"+ Arrays.toString(arr));
        insertSort(arr);
        System.out.println("排序后的数组:"+Arrays.toString(arr));
    }



    public static void insertSort(int[] arr){

        /*int tmp,i,j;
        for (i = 1; i < arr.length; i++) {
            tmp = arr[i];
            for (j = i -1; j >= 0 && arr[j] > tmp; j--) {
                arr[j+1] = arr[j];
            }
            arr[j+1] = tmp;
        }*/

        int len = arr.length;
        int preIndex, current;
        for(int i=0; i<len; i++){
            preIndex = i-1;
            current = arr[i];
            while(preIndex >= 0 && arr[preIndex] > current){
                arr[preIndex+1] = arr[preIndex];
                preIndex--;
            }
            arr[preIndex+1] = current;
        }
    }
}
